package com.xiaoshou.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xiaoshou.dao.IndexFile;
import com.xiaoshou.pojo.Answers;
import com.xiaoshou.pojo.Question;
import com.xiaoshou.pojo.QuestionFilesRel;
import com.xiaoshou.pojo.Questiontype;
import com.xiaoshou.pojo.User;
import com.xiaoshou.util.CreateTime;
import com.xiaoshou.util.MyUUID;
import com.xiaoshou.util.Outtime;
import com.xiaoshou.util.StringUtils;

@Service
@Transactional
public class QuestionService extends BaseService {

	private IndexFile indexFile;
	public final static String indexDirForQuestion = "F:\\工作相关索引\\销售索引";

	public List<Question> findQuestsList() {
		return getQuestionDao().findAllQuestion();
	}

	public List<Question> findQuestionsListByNowpage(int nowPage) {
		List<Question> list = getQuestionDao().findByNowPage(nowPage);
		for (Question question : list) {
			question.setOuttime(Outtime.OutDateTime(question.getUpdatetime()));
		}
		return list;
	}

	public void saveQuestion(String questionname, String questiontypeId,
			User user) {
		Questiontype qt = getQuestionTypeDao().findById(questiontypeId);

		Question q = new Question();
		q.setId(MyUUID.createUUID().toString());
		q.setCreatetime(CreateTime.createTime());
		q.setUpdatetime(q.getCreatetime());
		q.setQuestionname(StringUtils.replaceHtml(questionname));
		q.setUser(user);
		q.setQuestiontype(qt);
		getQuestionDao().saveNewQuestion(q);
		// 存完库添索引
		// 更新问题索引，即添加新的索引
		System.out
				.println("--------------------------------------------------------------------------------------------------------------------------");
		indexFile.updateIndexFileForQuestion(q);
	}

	public void updateQuestion(Question question, String questionTypeId) {
		Question delQuestionIndex = getQuestionDao().findById(question.getId());
		Questiontype qt = getQuestionTypeDao().findById(questionTypeId);
		
		Question q = getQuestionDao().findById(question.getId());
		q.setQuestionname(StringUtils.replaceHtml(question.getQuestionname()));
		q.setUpdatetime(CreateTime.createTime());
		q.setQuestiontype(qt);
		getQuestionDao().updateQuestion(q);
		// 删除该条索引,再更新该条索引
		IndexWriter writer = null;
		Analyzer sa = new SmartChineseAnalyzer(Version.LUCENE_40);
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, sa);
		Directory dir1 = null;
		try {
			dir1 = FSDirectory.open(new File(indexDirForQuestion));
			writer = new IndexWriter(dir1, iwc);
			Term term = new Term("id", delQuestionIndex.getId());
			writer.deleteDocuments(term);
			writer.commit();
			writer.close();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (LockObtainFailedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) {
					writer.close();
					sa.close();
				}
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// 添加新索引
		indexFile.updateIndexFileForQuestion(q);
	}

	public IndexFile getIndexFile() {
		return indexFile;
	}

	@Autowired
	public void setIndexFile(IndexFile indexFile) {
		this.indexFile = indexFile;
	}

	public void deleteQuestionById(String questionId) {

		FilesService fs = new FilesService();
		Question question = getQuestionDao().findById(questionId);
		// 刪除問題的答案
		List<Answers> list = question.getAnswerses();
		if (list != null) {
			for (Answers answers : list) {
				getAnswersDao().deleteAnswer(answers.getId());
			}
		}
		question.getQuestionFilesRels();
		// 删除问题中的文件,及删除上传文件夹中文件
		List<QuestionFilesRel> fileL = question.getQuestionFilesRels();
		System.out.println(fileL.size());
		if (fileL != null) {
			for (QuestionFilesRel filesQuestionRel : fileL) {
				// 删除文件夹中的文件
				// filesQuestionRel.getFiles().getFileurl();
				fs.delFileInTomcat(filesQuestionRel);
				// 删除库中的数据,关系表及有关表
				fs.delFilesOfQuestion(filesQuestionRel.getFiles());
			}
		}

		System.out
				.println("--------------------------------------------------------");
		getQuestionDao().del(questionId);// 去库中删除数据
		System.out.println("数据库中删除完，开始删索引" + questionId);
		// 删除该条索引,
		IndexWriter writer = null;
		Analyzer sa = new SmartChineseAnalyzer(Version.LUCENE_40);
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, sa);
		Directory dir1 = null;
		try {
			dir1 = FSDirectory.open(new File(indexDirForQuestion));
			writer = new IndexWriter(dir1, iwc);
			Term term = new Term("id", questionId);

			// Term term2 = new Term("questionname",);
			writer.deleteDocuments(term);
			writer.commit();
			writer.close();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
			System.out.println("删除索引失败1");
		} catch (LockObtainFailedException e) {
			System.out.println("删除索引失败2");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("删除索引失败3");
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) {
					writer.close();
					sa.close();
				}
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("索引删除完成");
	}

	public List<Question> findQuestionsTrendsBySales(User user) {
		List<Question> list = getQuestionDao().findQuestionsTrendsBySales(user);
		if(list!=null){
			
			for (Question question : list) {
				question.setOuttime(Outtime.OutDateTime(question.getUpdatetime()));
			}
			return list;
		}
		return null;
	}
}
